package com.networkmanagerj
{
	
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	
	import flexlib.mdi.containers.MDIWindow;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.UIComponent;
	import mx.events.CloseEvent;
	import mx.events.FlexEvent;
	import mx.events.ValidationResultEvent;
	import mx.messaging.messages.ErrorMessage;
	import mx.messaging.messages.RemotingMessage;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	import mx.validators.Validator;
	
	import spark.components.Button;
	import spark.components.TextInput;
	import spark.components.TitleWindow;
	import spark.components.supportClasses.SkinnableTextBase;
	
	public class GridViewMdiWindown extends MDIWindow
	{
		protected var TW_CAD_NEW:String = "TW_CAD_NEW";
		protected var BT_ADD:String = "BT_ADD";
		protected var BT_SAVE:String = "BT_SAVE";
		protected var BT_REFRESH:String = "BT_REFRESH";
		protected var BT_CANCEL:String = "BT_CANCEL";
		protected var GRID_VIEW:String = "GRID_VIEW";
		protected var MESSAGE_SAVE_SUCESS:String= "Dados salvos com sucesso!";
		protected var MESSAGE_UPDATE_SUCESS:String= "Dados alterados com sucesso!";
		protected var MESSAGE_DELETE_SUCESS:String= "Dados removidos com sucesso!";
		
		public var validators:ArrayCollection;
		protected var remoteObject:RemoteObject=null;
		[Bindable]
		protected var dataProvider:ArrayCollection;
		private var currentDataObject  : Object;
		
		public function GridViewMdiWindown()
		{
			super();
			addEventListener(FlexEvent.CREATION_COMPLETE,onCreateComplete);
			remoteObject = new RemoteObject("service");
			remoteObject.showBusyCursor=true;
			remoteObject.getOperation("save").addEventListener(ResultEvent.RESULT,operationSucess);
			remoteObject.getOperation("update").addEventListener(ResultEvent.RESULT,operationSucess);
			remoteObject.getOperation("deleteEntity").addEventListener(ResultEvent.RESULT,operationSucess);
			remoteObject.getOperation("getAll").addEventListener(ResultEvent.RESULT,operationSucess);
			remoteObject.getOperation("save").addEventListener(FaultEvent.FAULT,operationFailed);
			remoteObject.getOperation("update").addEventListener(FaultEvent.FAULT,operationFailed);
			remoteObject.getOperation("deleteEntity").addEventListener(FaultEvent.FAULT,operationFailed);
			remoteObject.getOperation("getAll").addEventListener(FaultEvent.FAULT,operationFailed);
		}
		
		
		protected function getChildByName2(name : String,child : UIComponent = null) : DisplayObject
		{
			var childAux : UIComponent;	
			var count : int;	
			var dpObject : DisplayObject = null;
			if(child == null)
				//child = UIComponent(this.getChildAt(0));
				child = this;
			count = child.numChildren;   
			
			if(child.name == name)
				return child;
			else   
				for(var i : int = 0;i<count;i++)
				{
					dpObject = child.getChildAt(i);
					
					if(dpObject is UIComponent)
					{
						childAux = UIComponent(this.getChildByName2(name,UIComponent(dpObject)));
						if(childAux != null)
							return childAux
					}
				}
			
			return childAux;   
		}	    
		
		protected function clearForm(child : UIComponent = null) : void
		{
			var childAux : UIComponent;	
			var count : int;	
			var dpObject : DisplayObject = null;
			if(child == null)
				child = this;
			count = child.numChildren;   
			
			for(var i : int = 0;i<count;i++)
				{
					dpObject = child.getChildAt(i);
					if(dpObject as mx.controls.TextInput|| dpObject as XvicTextInput){
						mx.controls.TextInput(dpObject).text = "";
					}else if(dpObject as spark.components.TextInput){
						SkinnableTextBase(dpObject).text = "";
					}
					if(dpObject is UIComponent)
					{
						childAux = UIComponent(this.clearForm(UIComponent(dpObject)));
					}
				}   
		}	
		
		protected function onCreateComplete(event:FlexEvent):void{		
			var obj:DisplayObject = getChildByName2(BT_ADD);
			if(obj!=null ){
				obj.addEventListener(MouseEvent.CLICK,btAddOnClick);
			}
			obj = getChildByName2(BT_REFRESH);
			if(obj!=null ){
				obj.addEventListener(MouseEvent.CLICK,btRefreshOnClick);
			}
			obj = getChildByName2(BT_CANCEL);
			if(obj!=null ){
				obj.addEventListener(MouseEvent.CLICK,btCancelOnClick);
			}
			
			obj = getChildByName2(TW_CAD_NEW);
			if(obj!=null){
				TitleWindow(obj).addEventListener(CloseEvent.CLOSE,twOnClose);
				obj.x = (screen.width - obj.width)/2;
				obj.y = (screen.height - obj.height)/2;
				
				var btSave:DisplayObject = getChildByName2(BT_SAVE);
				if(btSave!=null){
					Button(btSave).addEventListener(MouseEvent.CLICK,validate);		
				}
				obj.visible= false;
			}
			this.addEventListener(XvicGridEvents.ITEM_GRID_DELETE,this.gridItemDeleteEventHandler);
			this.addEventListener(XvicGridEvents.ITEM_GRID_EDIT,this.gridItemEditEventHandler);
			loadDataProvider();
		}
		
		protected function gridDelete(object : Object):void{
			remoteObject.deleteEntity(object);
		};
		
		protected function gridEdit(object : Object):void
		{
			setVisibleByName(TW_CAD_NEW,true);
		}
		
		private function gridItemEditEventHandler(event : XvicGridEvents):void
		{
			this.gridEdit(event.dataObject);
		}
		
		private function closeAlertEvent(event : CloseEvent) : void
		{
			if(event.detail == Alert.YES)
				this.gridDelete(this.currentDataObject);		      	
		}
		
		private function gridItemDeleteEventHandler(event : XvicGridEvents):void
		{
			this.currentDataObject = event.dataObject;	
			Alert.show("Deseja excluir o registro ?","Exclusão",Alert.YES+Alert.NO,null,this.closeAlertEvent);
		}
		
		protected function getAllSucess(event:ResultEvent):void{
			if(dataProvider==null){
				dataProvider = event.result as ArrayCollection;
			}
		}
		
		protected function closeTw():void{
			var obj:DisplayObject = getChildByName2(TW_CAD_NEW);
			if(obj!=null){
				TitleWindow(obj).closeButton.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			}
		}
		
		protected function operationSucess(event:ResultEvent):void{
			if(RemotingMessage(event.token.message).operation=="save"){
				Alert.show(MESSAGE_SAVE_SUCESS);
			}else if(RemotingMessage(event.token.message).operation=="update") {
				Alert.show(MESSAGE_UPDATE_SUCESS);
			}else if(RemotingMessage(event.token.message).operation=="deleteEntity"){
				Alert.show(MESSAGE_DELETE_SUCESS);
				loadDataProvider();
				return;
			}else if(RemotingMessage(event.token.message).operation=="getAll"){
				getAllSucess(event);
				return;
			}
			closeTw();
			clearForm();
			loadDataProvider();
		}
		
		protected function operationFailed(event:FaultEvent):void{
			var errorMessage:ErrorMessage = event.message as ErrorMessage;
			if(RemotingMessage(event.token.message).operation=="deleteEntity"){
				Alert.show(errorMessage.rootCause.message,"Erro ao excluir dados!");
			}else if(RemotingMessage(event.token.message).operation=="save"){
				Alert.show(errorMessage.rootCause.message,"Erro ao salvar dados!");
			}else if(RemotingMessage(event.token.message).operation=="update"){
				Alert.show(errorMessage.rootCause.message,"Erro ao alterar dados!");
			}else if(RemotingMessage(event.token.message).operation=="getAll"){
				Alert.show(errorMessage.rootCause.message,"Erro ao buscar dados!");
			}
		}
		
		protected function loadDataProvider():void{}
		
		protected function save():void{
			
		}
		
		protected function validate(event:MouseEvent):void{
			var retorno:Boolean= true; 
			for each(var validator:Validator in validators){
				var result:ValidationResultEvent = validator.validate();
				if(result.results!=null){
					retorno = false;
				}
			}
			if(!retorno){
				XvicAlert.showInfoAlert("Verifique os campos inválidos!",this.title);
			}else{
				save();
			}
		}
		
		public function btRefreshOnClick(event:MouseEvent):void{
			loadDataProvider();
		}
		
		public function btAddOnClick(event:MouseEvent):void{
			setVisibleByName(TW_CAD_NEW,true);
			clearForm();
		}
		
		public function btCancelOnClick(event:MouseEvent):void{
			setVisibleByName(TW_CAD_NEW,false);
			clearForm();
			currentDataObject = null;
		}
		
		public function twOnClose(event:CloseEvent):void{
			setVisibleByName(TW_CAD_NEW,false);
		}
		
		public function setVisibleByName(name:String,value:Boolean):DisplayObject{
			var obj:DisplayObject = getChildByName(name);
			if(obj!=null ){
				obj.visible = value;
				return obj;
			}
			return null;
		}
		
		protected function labelFunctionAtivo(item:Object, col:DataGridColumn):String{
			if(item.ativo)
				return "Sim";
			else
				return "Não";
		}
		
		protected function labelFunctionOnline(item:Object, col:DataGridColumn):String{
			if(item.online)
				return "Sim";
			else
				return "Não";
		}
	}
}